let cfg = require('../config')
const sqlserver = require('mssql')
const db = {

    getIdString: function (pre) {
        let id = pre;
        let s = new Date();
        id +=
            s.getFullYear().toString() +
            s.getMonth().toString() +
            s.getDate().toString() +
            s.getHours().toString();
        id +=
            s.getMinutes().toString() +
            s.getSeconds().toString() +
            s.getMilliseconds().toString() +
            Math.round(Math.random() * 1000).toString();
        const tsleep = (time) => {
            return new Promise(resolve => setTimeout(resolve, time))
        }
        tsleep(1)
        return id.slice(0, 20);
    },
    getTimeString: function (time) {

        return time.getFullYear().toString() + '-' +
            (time.getMonth() + 1).toString() + '-' +
            time.getDate().toString() + ' ' +
            time.getHours().toString() + ':' +

            time.getMinutes().toString() + ':' +
            time.getSeconds().toString()

    },
    dbConfigSource: {
        server: cfg.dicServer,
        database: 'MRFSQuery',
        user: 'sa',
        password: 'Docimax@123',
        port: 1433
    },

    querySql: async function (strsql) {
        try {
            //let pool = await getConnection()
            var pool = new sqlserver.ConnectionPool(this.dbConfigSource);
            await pool.connect();
            let request = pool.request();
            request.multiple = true;
            await request.query(strsql);

        } catch (error) {
            console.log(error);
        } finally {
            //await doRelease(pool);
            await sqlserver.close();
        }
    },
    saveTrace: async function (userid, type, spends, results, query) {

        try {
            let sql = `insert into Table_UserTrace 
        (UserID,Action,Value,Time)
         values
         ('` + userid + "','execute " + type + " spend:" + spends + ",results:" + results + "','" + (query) + "','" + this.getTimeString(new Date()) + "')";
            console.log(sql);
            await this.querySql(sql)
        } catch (err) {
            console.log(err);
        }
    }
}
module.exports = db;